package com.dayaokeji.rhythmschoolstudent.client.common.vote;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;

import com.dayaokeji.rhythmschoolstudent.R;
import com.dayaokeji.rhythmschoolstudent.client.common.ActivityStackManager;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.BaseActivity;
import com.dayaokeji.rhythmschoolstudent.client.common.vote.adapter.VoteItemAdapter;
import com.dayaokeji.rhythmschoolstudent.event.UpdateVoteEvent;
import com.dayaokeji.rhythmschoolstudent.utils.ServerCallback;
import com.dayaokeji.rhythmschoolstudent.utils.ToastUtils;
import com.dayaokeji.server_api.ApiUtils;
import com.dayaokeji.server_api.Page;
import com.dayaokeji.server_api.ServerResponse;
import com.dayaokeji.server_api.api.VoteApi;
import com.dayaokeji.server_api.domain.UserVote;
import com.dayaokeji.server_api.domain.Vote;
import com.dayaokeji.server_api.domain.VoteItem;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;

/**
 * 投票详情
 */
public class VoteDetailActivity extends BaseActivity {

    public static final String EXTRA_VOTE_ENTITY = "vote_entity";

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.rv_vote_sub_items)
    RecyclerView rvVoteSubItems;
    @BindView(R.id.tv_vote)
    TextView tvVote;

    private static final VoteApi voteApi = ApiUtils.getApi(VoteApi.class);
    private Call<ServerResponse<Void>> voteCall;
    private Vote vote;
    private Call<ServerResponse<Page<VoteItem>>> listOptionCall;
    private VoteItemAdapter voteItemAdapter;

    public static final Set<VoteItem> userSelectVote = new HashSet<>();
    private List<VoteItem> voteItemList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vote_detail);
        setSupportActionBar(toolbar);
        vote = (Vote) getIntent().getSerializableExtra(EXTRA_VOTE_ENTITY);

        if (vote == null) {
            ToastUtils.warning(R.string.data_incorrect);
            return;
        }

        init();
    }


    private void init() {
        initData();
        setRecyclerView();
        setOnListener();
        showVote();
    }

    private void showVote() {
        if (vote.getVoted() == 2) {
            tvVote.setEnabled(false);
            tvVote.setClickable(false);
            tvVote.setText("已投票");
        }else{
            tvVote.setEnabled(true);
            tvVote.setClickable(true);
            tvVote.setText("提交");
        }
    }

    private void setRecyclerView() {
        rvVoteSubItems.setLayoutManager(new LinearLayoutManager(this));
        voteItemAdapter = new VoteItemAdapter();
        rvVoteSubItems.setAdapter(voteItemAdapter);
    }

    private void initData() {
        userSelectVote.clear();
        tvTitle.setText("投票："+vote.getTitle());
        getVoteItemList();
    }

    private void setOnListener() {
        voteItemAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                VoteItem voteItem = (VoteItem) baseQuickAdapter.getData().get(i);
                if (isChoose()) {
                    if (vote.getType() == 1) {
                        if (userSelectVote.contains(voteItem)) {
                            userSelectVote.remove(voteItem);
                            voteItem.setCount(voteItem.getCount()-1);
                        }else{
                            userSelectVote.clear();
                            userSelectVote.add(voteItem);
                            voteItem.setCount(voteItem.getCount()+1);
                        }
                        baseQuickAdapter.notifyDataSetChanged();
                    }else{
                        if (userSelectVote.contains(voteItem)) {
                            userSelectVote.remove(voteItem);
                            voteItem.setCount(voteItem.getCount()-1);
                        }else{
                            if (userSelectVote.size() != vote.getType()) {
                                userSelectVote.add(voteItem);
                                voteItem.setCount(voteItem.getCount()+1);
                            }else {
                                ToastUtils.info("最多只能选"+vote.getType()+"项");
                            }
                        }
                    }

                }else{
                    ToastUtils.info("最多只能选"+vote.getType()+"项");
                }
                voteItemAdapter.notifyItemChanged(i);
            }
        });

        voteItemAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                VoteItem voteItem = (VoteItem) baseQuickAdapter.getData().get(i);
                if (isChoose()) {
                    if (vote.getType() == 1) {
                        if (userSelectVote.contains(voteItem)) {
                            userSelectVote.remove(voteItem);
                            voteItem.setCount(voteItem.getCount()-1);
                        }else{
                            userSelectVote.clear();
                            userSelectVote.add(voteItem);
                            voteItem.setCount(voteItem.getCount()+1);
                        }
                        baseQuickAdapter.notifyDataSetChanged();
                    }else{
                        if (userSelectVote.contains(voteItem)) {
                            userSelectVote.remove(voteItem);
                            voteItem.setCount(voteItem.getCount()-1);
                        }else{
                            if (userSelectVote.size() != vote.getType()) {
                                userSelectVote.add(voteItem);
                                voteItem.setCount(voteItem.getCount()+1);
                            }else{
                                if (vote.getType() == 1) {
                                    userSelectVote.clear();
                                    userSelectVote.add(voteItem);
                                    voteItem.setCount(voteItem.getCount()+1);
                                    baseQuickAdapter.notifyDataSetChanged();
                                }else{
                                    ToastUtils.info("最多只能选"+vote.getType()+"项");
                                }

                            }
                        }
                    }


                }else{
                    ToastUtils.info("最多只能选"+vote.getType()+"项");
                }
                voteItemAdapter.notifyItemChanged(i);

            }
        });
    }

    private boolean isChoose() {
        if (userSelectVote.size() <= vote.getType()) {
            return true;
        }
        return false;
    }

    @OnClick({
            R.id.tv_vote,
            R.id.tv_see_vote_result
    })
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_vote:
                vote();
                break;
            case R.id.tv_see_vote_result:
                if (voteItemList != null) {
                    Intent intent = new Intent(VoteDetailActivity.this, VoteResultActivity.class);
                    intent.putExtra(VoteResultActivity.EXTRA_VOTE_TITLE,vote.getTitle());
                    intent.putExtra(VoteResultActivity.EXTRA_VOTE_LIST, (Serializable) voteItemList);
                    startActivity(intent);
                }
                break;
        }
    }

    /**
     * 投票子项数据
     */
    private void getVoteItemList() {
        listOptionCall = voteApi.listOption(vote.getId(), vote.getTitle(), 1, 100);
        listOptionCall.enqueue(new ServerCallback<Page<VoteItem>>(this,"正在加载数据...") {
            @Override
            public void onResponse(boolean success, ServerResponse<Page<VoteItem>> response) {
                if (success) {
                    if (voteItemAdapter != null) {
                        voteItemList = response.getBody().getList();
                        voteItemAdapter.setNewData(voteItemList);
                    }
                }
            }
        });
    }

    /**
     * 投票
     */
    private void vote() {
        if (userSelectVote.size() == 0) {
            ToastUtils.warning("请选择投票项");
            return;
        }
        UserVote userVote = new UserVote();
        userVote.setId(vote.getId());
        userVote.setOptionList(getUserSelectList());
        voteCall = voteApi.vote(userVote);
        voteCall.enqueue(new ServerCallback<Void>() {
            @Override
            public void onResponse(boolean success, ServerResponse<Void> response) {
                if (success) {
                    ToastUtils.success(getString(R.string.vote_success));
                    EventBus.getDefault().post(new UpdateVoteEvent());
                    ActivityStackManager.finish();
                }
            }
        });
    }

    /**
     * 将用户选择的Item，取选项ID
     * @return
     */
    private List<Integer> getUserSelectList() {
        ArrayList<Integer> list = new ArrayList<>();
        for (VoteItem voteItem : userSelectVote) {
            list.add(voteItem.getId());
        }
        return list;
    }


    @Override
    protected void onDestroy() {
        if (voteCall != null) {
            voteCall.cancel();
        }
        if (listOptionCall != null) {
            listOptionCall.cancel();
        }
        super.onDestroy();
    }
}
